//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { useDragonFlyStores } from './store/index';
import { useLocation } from "react-router-dom";
import { Button, Form, Input, Select, Switch, Tabs } from "antd";
import { appWindow } from "@tauri-apps/api/window";
import PortInfoPanel from "./PortInfoPanel";
import MemberPanel from "./MemberPanel";
import AuthSecretPanel from "./AuthSecretPanel";
import TracePanel from "./TracePanel";
import type { ServiceInfo } from "@/api/dragonfly/trace";
import { list_service, list_root_span_name, SORT_BY_CONSUME_TIME, SORT_BY_START_TIME } from "@/api/dragonfly/trace";
import { get_session } from "@/api/user";
import { gen_access_token } from "@/api/project_server";
import { request } from "@/utils/request";
import moment from "moment";
import { SearchOutlined } from "@ant-design/icons";

const DragonFlyApp = () => {
    const appStore = useDragonFlyStores();

    const [activeKey, setActiveKey] = useState("trace");
    const [serviceList, setServiceList] = useState<ServiceInfo[]>([]);
    const [rootSpanNameList, setRootSpanNameList] = useState<string[]>([]);
    const [curTraceId, setCurTraceId] = useState("");

    const location = useLocation();
    const urlParams = new URLSearchParams(location.search);
    const adminStr = urlParams.get("admin") ?? "false";
    const projectId = urlParams.get("projectId") ?? "";
    const remoteId = urlParams.get("remoteId") ?? "";

    const loadServiceList = async () => {
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));
        const pasthour = appStore.traceFilter?.timeFilter?.pastHour ?? 1;
        const res = await request(list_service(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            from_time: moment().subtract(pasthour, "hours").valueOf(),
            to_time: moment().valueOf(),
        }));
        res.service_list.sort((a, b) => {
            const keya = `${a.service_name}:${a.service_version}`;
            const keyb = `${b.service_name}:${b.service_version}`;
            return keya.localeCompare(keyb);
        });
        setServiceList(res.service_list);
        if (res.service_list.length > 0 && appStore.traceFilter == null) {
            appStore.traceFilter = {
                serviceInfo: res.service_list[0],
                filterByTraceId: false,
                timeFilter: {
                    pastHour: 1,
                    rootSpanName: "",
                    sortBy: SORT_BY_CONSUME_TIME,
                },
            };
        }
    };

    const loadRootSpanNameList = async () => {
        if (appStore.traceFilter == null) {
            return;
        }
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));
        const pasthour = appStore.traceFilter?.timeFilter?.pastHour ?? 1;
        const res = await request(list_root_span_name(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            service: appStore.traceFilter.serviceInfo,
            from_time: moment().subtract(pasthour, "hours").valueOf(),
            to_time: moment().valueOf(),
        }));
        res.name_list.sort((a, b) => a.localeCompare(b));
        setRootSpanNameList(res.name_list);
    };

    useEffect(() => {
        appStore.init(projectId, remoteId, adminStr.toLowerCase().startsWith("t"))
    }, [adminStr, projectId, remoteId]);

    useEffect(() => {
        appWindow.setAlwaysOnTop(false);
    }, []);

    useEffect(() => {
        loadServiceList();
    }, [appStore.remoteServer, appStore.traceFilter?.timeFilter?.pastHour]);

    useEffect(() => {
        if (appStore.traceFilter != null && appStore.traceFilter.filterByTraceId == false) {
            loadRootSpanNameList();
        }
    }, [appStore.remoteServer, appStore.traceFilter?.serviceInfo]);

    return (
        <>
            {appStore.remoteServer != null && (
                <Tabs activeKey={activeKey} onChange={key => {
                    setActiveKey(key);
                    if (key == "trace") {
                        loadServiceList();
                    }
                }} type="card" tabBarStyle={{ height: "40px" }} style={{ padding: "0px 0px" }}
                    tabBarExtraContent={
                        <>
                            {activeKey == "trace" && appStore.traceFilter != null && (
                                <Form layout="inline">
                                    <Form.Item label="按ID查询">
                                        <Switch size="small" checked={appStore.traceFilter.filterByTraceId} onChange={checked => {
                                            setCurTraceId("");
                                            if (appStore.traceFilter != null) {
                                                appStore.traceFilter = {
                                                    ...appStore.traceFilter,
                                                    filterByTraceId: checked,
                                                    traceId: "",
                                                };
                                            }
                                        }} />
                                    </Form.Item>
                                    <Form.Item label="服务">
                                        <Select value={`${appStore.traceFilter.serviceInfo.service_name}:${appStore.traceFilter.serviceInfo.service_version}`} onChange={value => {
                                            if (appStore.traceFilter != null) {
                                                serviceList.forEach(svcItem => {
                                                    const key = `${svcItem.service_name}:${svcItem.service_version}`;
                                                    if (key == value && appStore.traceFilter != null) {
                                                        appStore.traceFilter = {
                                                            ...appStore.traceFilter,
                                                            serviceInfo: svcItem,
                                                        };
                                                    }
                                                });
                                            }
                                        }} style={{ width: "150px" }}>
                                            {serviceList.map(svcItem => (
                                                <Select.Option key={`${svcItem.service_name}:${svcItem.service_version}`} value={`${svcItem.service_name}:${svcItem.service_version}`}>{svcItem.service_name}({svcItem.service_version})</Select.Option>
                                            ))}
                                        </Select>
                                    </Form.Item>
                                    {appStore.traceFilter.filterByTraceId == false && appStore.traceFilter.timeFilter != undefined && (
                                        <Form.Item label="名称">
                                            <Select value={appStore.traceFilter.timeFilter.rootSpanName} onChange={value => {
                                                if (appStore.traceFilter != null && appStore.traceFilter.filterByTraceId == false && appStore.traceFilter.timeFilter != undefined) {
                                                    appStore.traceFilter = {
                                                        ...appStore.traceFilter,
                                                        timeFilter: {
                                                            ...appStore.traceFilter.timeFilter,
                                                            rootSpanName: value,
                                                        },
                                                    };
                                                }
                                            }} style={{ width: "150px" }}>
                                                <Select.Option value="">全部</Select.Option>
                                                {rootSpanNameList.map(rootSpanName => (
                                                    <Select.Option key={rootSpanName} value={rootSpanName}>{rootSpanName}</Select.Option>
                                                ))}
                                            </Select>
                                        </Form.Item>
                                    )}
                                    {appStore.traceFilter.filterByTraceId == false && appStore.traceFilter.timeFilter != undefined && (
                                        <Form.Item label="最近">
                                            <Select value={appStore.traceFilter.timeFilter.pastHour} onChange={value => {
                                                if (appStore.traceFilter != null && appStore.traceFilter.filterByTraceId == false && appStore.traceFilter.timeFilter != undefined) {
                                                    appStore.traceFilter = {
                                                        ...appStore.traceFilter,
                                                        timeFilter: {
                                                            ...appStore.traceFilter.timeFilter,
                                                            pastHour: value,
                                                        },
                                                    };
                                                }
                                            }} style={{ width: "80px" }}>
                                                <Select.Option value={1}>1小时</Select.Option>
                                                <Select.Option value={6}>6小时</Select.Option>
                                                <Select.Option value={12}>12小时</Select.Option>
                                                <Select.Option value={24}>1天</Select.Option>
                                                <Select.Option value={24 * 3}>3天</Select.Option>
                                                <Select.Option value={24 * 7}>7天</Select.Option>
                                            </Select>
                                        </Form.Item>
                                    )}
                                    {appStore.traceFilter.filterByTraceId == false && appStore.traceFilter.timeFilter != undefined && (
                                        <Form.Item label="排序">
                                            <Select value={appStore.traceFilter.timeFilter.sortBy} onChange={value => {
                                                if (appStore.traceFilter != null && appStore.traceFilter.filterByTraceId == false && appStore.traceFilter.timeFilter != undefined) {
                                                    appStore.traceFilter = {
                                                        ...appStore.traceFilter,
                                                        timeFilter: {
                                                            ...appStore.traceFilter.timeFilter,
                                                            sortBy: value,
                                                        },
                                                    };
                                                }
                                            }} style={{width:"90px"}}>
                                                <Select.Option value={SORT_BY_CONSUME_TIME}>消耗时间</Select.Option>
                                                <Select.Option value={SORT_BY_START_TIME}>请求时间</Select.Option>
                                            </Select>
                                        </Form.Item>
                                    )}
                                    {appStore.traceFilter.filterByTraceId == true && (
                                        <Form.Item label="TraceId">
                                            <Input value={curTraceId} onChange={e => {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                setCurTraceId(e.target.value.trim());
                                            }} onKeyDown={e => {
                                                if (e.key == "Enter") {
                                                    if (appStore.traceFilter != null) {
                                                        appStore.traceFilter = {
                                                            ...appStore.traceFilter,
                                                            traceId: curTraceId,
                                                        };
                                                    }
                                                }
                                            }} suffix={
                                                <Button type="primary" icon={<SearchOutlined />} style={{ minWidth: "0px", width: "20px", height: "20px", borderRadius: "4px" }}
                                                    disabled={curTraceId == ""}
                                                    onClick={e => {
                                                        e.stopPropagation();
                                                        e.preventDefault();
                                                        if (appStore.traceFilter != null) {
                                                            appStore.traceFilter = {
                                                                ...appStore.traceFilter,
                                                                traceId: curTraceId,
                                                            };
                                                        }
                                                    }} />
                                            } />
                                        </Form.Item>
                                    )}
                                </Form>
                            )}
                        </>
                    }>
                    <Tabs.TabPane tab={<span style={{ fontSize: "16px" }}>链路追踪数据</span>} key="trace">
                        {activeKey == "trace" && (
                            <TracePanel />
                        )}
                    </Tabs.TabPane>
                    {appStore.adminUser && (
                        <Tabs.TabPane tab={<span style={{ fontSize: "16px" }}>成员管理</span>} key="member">
                            {activeKey == "member" && (
                                <div style={{ height: "calc(100vh - 50px)", overflowY: "scroll" }}>
                                    <MemberPanel />
                                </div>
                            )}
                        </Tabs.TabPane>
                    )}

                    <Tabs.TabPane tab={<span style={{ fontSize: "16px" }}>密钥管理</span>} key="secret">
                        {activeKey == "secret" && (
                            <div style={{ height: "calc(100vh - 50px)", overflowY: "scroll" }}>
                                <AuthSecretPanel />
                            </div>
                        )}
                    </Tabs.TabPane>

                    <Tabs.TabPane tab={<span style={{ fontSize: "16px" }}>服务信息</span>} key="info">
                        {activeKey == "info" && (
                            <div style={{ height: "calc(100vh - 50px)", overflowY: "scroll" }}>
                                <PortInfoPanel />
                            </div>
                        )}
                    </Tabs.TabPane>
                </Tabs>
            )}
        </>
    );
};

export default observer(DragonFlyApp);